<template>
  <div class="job-center">
    <!-- 返回按钮（当显示Task列表或从WorkerNode进入时显示） -->
    <button 
      v-if="!showTaskList && fromWorkerNode" 
      @click="handleBack"
      class="back-btn"
    >
      返回
    </button>
    
    <!-- 创建Job按钮（仅当不显示Task列表且不从WorkerNode进入时显示） -->
    <button 
      v-if="!showTaskList && !showCreateJobForm && !fromWorkerNode" 
      class="create-btn" 
      @click="showCreateJob"
    >
      创建Job
    </button>
    
    <!-- Job列表（仅当不显示创建表单和Task列表时显示） -->
    <JobList 
      v-if="!showCreateJobForm && !showTaskList"
      :env_id="env_id" 
      @show-task-details="showTaskDetails"
    />
    
    <!-- Task列表 -->
    <TaskList 
      v-if="showTaskList" 
      :job_id="selectedJobId" 
      @go-back="hideTaskDetails"
    />
    
    <!-- 创建Job表单 -->
    <CreateJob 
      v-if="showCreateJobForm" 
      :env_id="env_id" 
      @go-back="hideCreateJobForm"
      @job-submitted="hideCreateJobForm"
    />
  </div>
</template>

<script>
import { ref } from 'vue'
import JobList from './JobList.vue'
import TaskList from './TaskList.vue'
import CreateJob from './CreateJob.vue'

export default {
  components: { JobList, TaskList, CreateJob },
  props: {
    env_id: {
      type: String,
      required: true
    },
    worker_id: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    const showTaskList = ref(false)
    const selectedJobId = ref('')
    const showCreateJobForm = ref(false)
    const fromWorkerNode = ref(!!props.worker_id) // 判断是否从WorkerNode进入

    const showTaskDetails = (job_id) => {
      selectedJobId.value = job_id
      showTaskList.value = true
    }

    const hideTaskDetails = () => {
      showTaskList.value = false
      if (fromWorkerNode.value) {
        emit('go-back') // 如果是从WorkerNode进入，则通知父组件返回
      }
    }

    const showCreateJob = () => {
      showCreateJobForm.value = true
    }

    const hideCreateJobForm = () => {
      showCreateJobForm.value = false
    }

    const handleBack = () => {
      if (showTaskList.value) {
        hideTaskDetails()
      } else {
        emit('go-back') // 直接返回WorkerNode列表
      }
    }

    return {
      showTaskList,
      selectedJobId,
      showCreateJobForm,
      fromWorkerNode,
      showTaskDetails,
      hideTaskDetails,
      showCreateJob,
      hideCreateJobForm,
      handleBack
    }
  }
}
</script>

<style scoped>
.job-center {
  padding: 20px;
  position: relative;
}

.back-btn {
  padding: 8px 16px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 15px;
  cursor: pointer;
}

.back-btn:hover {
  background-color: #e0e0e0;
}

.create-btn {
  padding: 10px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  margin-bottom: 20px;
  cursor: pointer;
}

.create-btn:hover {
  opacity: 0.9;
}
</style>